﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SHKF.B2C.BaseHosted;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.BLL.SugarIOC;
using SHKF.B2C.Hosted;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Dto.Center;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.YouZanYun.Model.Inter.Center;
using SqlSugar;
using System;
using System.Collections.Generic; 
using System.Threading.Tasks; 

namespace SHKF.B2C.Mannage.Service.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class ProductController : BaseController
    {
        private readonly ProductBaseBLL productBaseBLL;
        private readonly ProductInfoBLL productInfoBLL;
        private readonly ShopBLL shopBLL;
        private readonly ShopMapBLL shopCBLL;

        public ProductController(
            ProductBaseBLL productBaseBLL,
            ProductInfoBLL productInfoBLL,
            ShopBLL shopBLL,
            ShopMapBLL shopCBLL,
            ILogger<ProductController> logger) :base(logger)
        {
            this.productBaseBLL = productBaseBLL;
            this.productInfoBLL = productInfoBLL;
            this.shopBLL = shopBLL;
            this.shopCBLL = shopCBLL;
        }

        [HttpGet("list")]
        public ProductListDto List(int CompnaySN, long ShopSN, string ProductName)
        {
            ProductListDto dto = new ProductListDto();

            try
            { 
                dto.data = this.productInfoBLL.Query(CompnaySN, ShopSN, ProductName); 
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }

        [HttpPost("Save")]
        public ProductInfoDto Save(ProductInfoEntity productInfo)
        {
            ProductInfoDto dto = new ProductInfoDto();

            try
            {
                productInfo = this.productInfoBLL.Save(productInfo); 
                dto.data = productInfo;
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }

        //[HttpPost("SaveAndMap")]
        //public async Task<DataDto> SaveAndMap(ProductAndMapEntity data)
        //{
        //    DataDto dto = new DataDto();

        //    try
        //    {
        //        //保存商品库
        //        ProductBaseEntity productBase = data.ProductInfo;

        //        //如果已经存在则用商品库的信息
        //        ProductBaseEntity oldInfo = this.productBaseBLL.Get(data.ProductInfo.Upc);
        //        if (oldInfo != null)
        //        {
        //            productBase.ProductName = oldInfo.ProductName;
        //            productBase.Upc = oldInfo.Upc;
        //            productBase.LiceseId = oldInfo.LiceseId;
        //            productBase.Spec = oldInfo.Spec;
        //            productBase.Price = oldInfo.Price;
        //            productBase.Made = oldInfo.Made;
        //            productBase.Unit = oldInfo.Unit;
        //            productBase.Model = oldInfo.Model;
        //            productBase.Manufacturer = oldInfo.Manufacturer;

        //            productBase.Validate = oldInfo.Validate;
        //            productBase.CommonTitle = oldInfo.CommonTitle;
        //            productBase.ConditionOfStorage = oldInfo.ConditionOfStorage; ;
        //            productBase.Prescript = oldInfo.Prescript;

        //            productBase.Brand = oldInfo.Brand;
        //            productBase.Functions = oldInfo.Functions;
        //            productBase.Ingredients = oldInfo.Ingredients;
        //            productBase.UsageDosage = oldInfo.UsageDosage;
        //            productBase.Taboo = oldInfo.Taboo;
        //            productBase.Packing = oldInfo.Packing;
        //            productBase.SN = oldInfo.SN;
        //        }
        //        else
        //        {
        //            productBase = this.productBaseBLL.Save(productBase);
        //        }

        //        int CompanySN = data.ProductInfo.CompanySN;

        //        //保存总部产品信息
        //        ProductInfoEntity productInfo0 = new ProductInfoEntity();
        //        productInfo0.ShopSN  = 0;
        //        productInfo0.CompanySN = CompanySN;
        //        productInfo0.ID = data.ProductInfo.ID;
        //        productInfo0.FKSN = productBase.SN;
        //        this.productInfoBLL.Save(productInfo0);

        //        data.Map.FKSN = productInfo0.SN;
        //        this.productInfoBLL.MapSave(data.Map);

        //        //保存所有的店铺商品 
        //        foreach (ShopEntity shopEntity in this.shopBLL.Query(CompanySN, "") )
        //        {
        //            //保存店铺商品
        //            ProductInfoEntity productInfo = new ProductInfoEntity();
        //            productInfo.ShopSN = shopEntity.ShopSN;
        //            productInfo.CompanySN = CompanySN;
        //            productInfo.ID = data.ProductInfo.ID;
        //            productInfo.FKSN = productBase.SN; 
        //            this.productInfoBLL.Save(productInfo);

        //            ItemsDto dto2 = await this.httpClient.ItemSearch(strPoiCode, productInfo.ID);

        //            //保存映射表
        //            ProductInfoMapEntity map = new ProductInfoMapEntity();
        //            map.Platform = PlatformEnum.YouZanYun;
        //            map.app_medicine_code = "";
        //            map.Upc = productBase.Upc;
        //            map.FKSN = productInfo.SN;
        //            this.productInfoBLL.MapSave(map); 
        //        } 
        //    }
        //    catch (Exception ex)
        //    {
        //        dto.error = new Error() { code = -1, msg = ex.Message };
        //        base.WriteException("List", ex);
        //    }

        //    return dto;
        //}

        [HttpPost("batch/delete")]
        public DataDto BatchDelete(List<ProductInfoEntity> products)
        {
            DataDto dto = new DataDto();

            try
            { 
                if (products != null && products.Count > 0)
                {
                    foreach (ProductInfoEntity product in products)
                    {
                        //this.productInfoBLL.platform = product.Platform;
                        this.productInfoBLL.Delete(product);
                    }
                }
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }

        [HttpGet("map/list")]
        public ProductInfoMapListDto MapList(long FKSN)
        {
            ProductInfoMapListDto dto = new ProductInfoMapListDto();

            try
            {
                dto.data = this.productInfoBLL.MapQuery(FKSN);
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }

        [HttpPost("map/save")]
        public ProductInfoMapListDto MapSave(ProductInfoMapEntity productInfoMap)
        {
            ProductInfoMapListDto dto = new ProductInfoMapListDto();

            try
            {
                dto.data = this.productInfoBLL.MapSave(productInfoMap);
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }

        [HttpGet("map/delete")]
        public ProductInfoMapListDto MapDelete(long SN)
        {
            ProductInfoMapListDto dto = new ProductInfoMapListDto();

            try
            {
                dto.data = this.productInfoBLL.MapDelete(SN);
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }

            return dto;
        }

        [HttpGet("erp/list")]
        public ErpProductInfoListDto ErpList(string ServerName, string warehousSN, string KeyWord)
        {
            ErpProductInfoListDto dto = new ErpProductInfoListDto();
            try
            {
                SqlSugarClient db = DbScoped.CreateSugar(ServerName);
                if( db != null)
                {
                    db.ChangeDatabase("YZ_Med_InfoCenter");
                    List<ErpProductInfo> list = new List<ErpProductInfo>();
                    if (ServerName.Contains("Retail")) //如果是零售
                    {
                        string sql = $"select p.* from ProductInfo p inner join company c on c.sn = p.companysn inner join shop s on s.companysn = c.sn ";
                        sql += "where c.DeleteFlag = 0 and p.DeleteFlag = 0 and s.DeleteFlag = 0 ";
                        sql += $"and s.SN = {warehousSN} ";
                        sql += "and (p.ProductName like '%"+KeyWord+"%' ";
                        sql += "or p.Made like '%" + KeyWord + "%' ";
                        sql += "or p.Model like '%" + KeyWord + "%' ";
                        sql += "or p.Spec like '%" + KeyWord + "%' ";
                        sql += "or p.Unit like '%" + KeyWord + "%' ";
                        sql += "or p.Manufacturer like '%" + KeyWord + "%') ";

                        list = db.SqlQueryable<ErpProductInfo>(sql).ToList();
                    }
                    else
                    {
                        list = db.Queryable<ErpProductInfo>()
                      .Where(ww => ww.DeleteFlag == 0 && (ww.ProductName.Contains(KeyWord)
                                || ww.Made.Contains(KeyWord)
                                || ww.Model.Contains(KeyWord)
                                || ww.Spec.Contains(KeyWord)
                                || ww.Unit.Contains(KeyWord)
                                || ww.Manufacturer.Contains(KeyWord)))
                      .ToList();
                    } 
                    dto.data = list;
                } 
            }
            catch (Exception ex)
            {
                dto.error = new Error() { code = -1, msg = ex.Message };
            }
            return dto;
        }
    }
}
